package com.ww.scm.repository.mat;

import java.util.Date;

import org.springframework.stereotype.Component;

import com.ww.core.exception.ServiceException;
import com.ww.core.orm.hibernate.HibernateDao;
import com.ww.core.utils.DateUtils;
import com.ww.scm.constants.Constants;
import com.ww.scm.entity.mat.Account;
import com.ww.scm.entity.mat.Bill;
import com.ww.scm.entity.mat.Storage;
import com.ww.scm.entity.mat.Transaction;
import com.ww.scm.entity.mat.TransactionDetail;
import com.ww.scm.entity.pub.Dictionary;

//Spring Bean的标识.
@Component
public class AccountRepository extends HibernateDao<Account, String>{

	public Account createAccount(TransactionDetail transactionDetail,boolean output,String operator) {
		Date nowDate = new Date();
		
		Account account= new Account();
		Transaction transaction=transactionDetail.getTransaction();
		if (transaction==null){
			logger.error("创建帐目时事务对象为空!");
			throw new ServiceException("创建帐目时事务对象为空!");
		}
		Bill bill=transaction.getBill();
		if (bill==null){
			logger.error("创建帐目时单据对象为空!");
			throw new ServiceException("创建帐目时单据对象为空!");
		}
		Storage storage=transactionDetail.getStorage();
		if (storage==null){
			logger.error("创建帐目时事务对象为空!");
			throw new ServiceException("创建帐目时事务对象为空!");
		}
		Dictionary materiel = transactionDetail.getMateriel();
		if (materiel==null){
			logger.error("创建帐目时物料对象为空!");
			throw new ServiceException("创建帐目时物料对象为空!");
		}
		
		account.setBill(bill);
		account.setBillDate(bill.getBillDate());
		account.setTransaction(transaction);
		account.setTransactionDetail(transactionDetail);
		account.setStorage(storage);
		account.setMateriel(materiel);
		account.setOriginEntity(transactionDetail.getOriginEntity());
		account.setTargetEntity(transactionDetail.getTargetEntity());
		Double amount=transactionDetail.getAmount();
		if (output==false){
			amount=-amount;
		}
		account.setAmount(amount);
		account.setSysFlag(Constants.SYS_FLAG_USEING);
		account.setCreator(operator);
		account.setLastModifier(operator);
		account.setCreateTime(DateUtils.formatDateHms(nowDate));
		account.setLastModifiedTime(DateUtils.formatDateHms(nowDate));
		save(account);
		return account;
	}

	public Account rollbackAccount(TransactionDetail transactionDetail,boolean output,String operator) {
		Account account=createAccount(transactionDetail,!output,operator);
		return account;
	}
	
}
